package com.se7en.ufutil;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.loopj.android.http.AsyncHttpResponseHandler;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class StudyDisplay extends Activity implements OnClickListener {
		//Date and comments
		//private String[] comments;
		TextView title;
		Intent intent;
		String studyLocName;
		int studyID;
		String deviceID;
		ListView commentList;
		StudyComment[] comments;
		RatingBar overallratingbar;
		RatingBar quietratingbar;
		RatingBar crowdratingbar;

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			
		}
	
		public void onCreate(Bundle savedInstanceState) {
			intent = getIntent();
			super.onCreate(savedInstanceState);
			setContentView(R.layout.study);
			studyLocName = intent.getStringExtra("name");
			title = (TextView) findViewById(R.id.studytitle);
			title.setText(studyLocName);
			studyID = DataAccess.getStudyID(studyLocName);
			overallratingbar = (RatingBar) findViewById(R.id.overallrating);
			quietratingbar = (RatingBar) findViewById(R.id.quietrating);
			crowdratingbar = (RatingBar) findViewById(R.id.crowdedrating);
			updateComments(studyID, this);
			updateRatings(studyID, this);
			//comments = DataAccess.getComments(studyID);
			//if (comments[0] == null) comments[0] = "No comments"; 
			//StudyComment[] comments = new StudyComment[] {new StudyComment("11/24/11","Very quiet environment"), new StudyComment("11/27/11","Awesome library")  };
			//StudyComment[] comments = DataAccess.getComments(studyID);
			deviceID = "35" +
		        	Build.BOARD.length()%10+ Build.BRAND.length()%10 +
		        	Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
		        	Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
		        	Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
		        	Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
		        	Build.TAGS.length()%10 + Build.TYPE.length()%10 +
		        	Build.USER.length()%10;
			
			
			//Toast.makeText(StudyDisplay.this, deviceID, Toast.LENGTH_LONG).show();
			
			
			//overallratingbar.setRating(ratings[0]);
			//quietratingbar.setRating(ratings[1]);
			//crowdratingbar.setRating(ratings[2]);
			
			
			
			Button b = (Button) findViewById(R.id.commentform);
			b.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent newIntent = new Intent(v.getContext(),CommentForm.class);
					newIntent.putExtra("name", studyLocName);
					newIntent.putExtra("id", studyID);
					newIntent.putExtra("deviceID", deviceID);
					
					v.getContext().startActivity(newIntent);
					
				}
			});
		}
		private void updateComments(final int id, final Context c) {

			String url = "comments.php?action=fetch&sa="+Integer.toString(id);
	        myHttpClient.get(url, null, new AsyncHttpResponseHandler() {
	            @Override
	            public void onSuccess(String json) {
	        		JSONTokener tokener = new JSONTokener(json);
	        		JSONArray finalResult = null;
	        		try {
	        			finalResult = new JSONArray(tokener);
	        		} catch (JSONException e) {
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
	        		ArrayList<String[]> com1 = new ArrayList<String[]>();
	        		for (int i=0; i<finalResult.length(); i++){
	        			JSONObject jsonObject = null;
	        			String[] item = null;
	        			try {
	        				jsonObject = finalResult.getJSONObject(i);
	        				item = new String[] {jsonObject.getString("text"),jsonObject.getString("time")};
	        				
	        			} catch (JSONException e) {
	        				// TODO Auto-generated catch block
	        				e.printStackTrace();
	        			}
	        			com1.add(item);
	        		}
	        		comments = new StudyComment[com1.size()];
	    			for (int i=0; i<com1.size(); i++) {
	    				//I'll fix the dates on the server
	    				comments[i] = new StudyComment(com1.get(i)[1],com1.get(i)[0]);
	    			}
	    			commentList = (ListView) findViewById(R.id.commentview);
	    			StudyAdapter adapter = new StudyAdapter(c, R.layout.comment_row, comments);
	    			commentList.setAdapter(adapter);
	            }
	        });
		}
		
		private void updateRatings(final int id, final Context c) {

			String url = "comments.php?action=fetchr&sa="+Integer.toString(id);
	        myHttpClient.get(url, null, new AsyncHttpResponseHandler() {
	            @Override
	            public void onSuccess(String json) {
	        		JSONTokener tokener = new JSONTokener(json);
	        		JSONArray finalResult = null;
	        		try {
	        			finalResult = new JSONArray(tokener);
	        		} catch (JSONException e) {
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
	        		JSONObject jsonObject = null;
	        		try {
	        			jsonObject = finalResult.getJSONObject(0);
	        		} catch (JSONException e) {
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
	                try {
	                	overallratingbar.setRating((float) jsonObject.getDouble("o"));
	        		} catch (JSONException e) {
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
	                try {
	                	quietratingbar.setRating((float) jsonObject.getDouble("q"));
	        		} catch (JSONException e) {
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
	                try {
	                	crowdratingbar.setRating((float) jsonObject.getDouble("c"));
	        		} catch (JSONException e) {
	        			// TODO Auto-generated catch block
	        			e.printStackTrace();
	        		}
	            }
	        });
		}
		
}
